package com.itheima.reggie.service.impl;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired(required = false)
    AddressBookMapper addressBookMapper;
    @Override
    public void save(AddressBook addressBook) {
        addressBookMapper.save(addressBook);
    }

    @Override
    public List<AddressBook> list(Long userId) {
        return addressBookMapper.list(userId);
    }

    @Override
    public AddressBook findById(Long id) {
        return addressBookMapper.findById(id);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBookMapper.update(addressBook);
    }

    @Override
    public void updateDefault(AddressBook addressBook) {
        //1. 把该用户地址全部修改为非默认
        addressBookMapper.removeDefaultAddress(addressBook.getUserId());
        //2 重新设置当前地址为默认地址
        addressBookMapper.updateDefaultAddress(addressBook);
    }

    @Override
    public AddressBook getDefaultAddress(Long userId) {
        return addressBookMapper.getDefaultAddress(userId);

    }

    @Override
    public void deleteById(Long ids) {
        AddressBook addressBook = addressBookMapper.findById(ids);
        if (addressBook.getIsDefault() == 1){
            throw new CustomException("默认地址无法删除");
        }
        addressBookMapper.deleteById(ids);
    }
}
